package controllers;

import play.*;
import play.mvc.*;
import play.data.validation.*;

import java.util.*;

import models.*;
import models.User.Role;

public class Application extends Controller {

	protected static User connectedUser;

	@Before
	static void addDefaults() {
		renderArgs.put("appname", Play.configuration.getProperty("service.name"));
	}
	
	@Before()
	static void setConnectedUser() {
		connectedUser = connectedUser();
		renderArgs.put("currentUser", connectedUser);
		renderArgs.put("userRole", identifyUser());
	}

	public static void login() {
		render();
	}

	public static void authenticate(String user_name, String password) {
		User user = User.findByUsername(user_name);
		if (user == null || !user.checkPassword(password)) {
			flash.error("Bad username or bad password");
			flash.put("Username", user_name);
			login();
		}
		
		connect(user);
		flash.success("Welcome back %s !", user.userName);
		
		index();
	}

	public static void logout() {
		flash.success("You've been logged out");
		session.clear();
		index();
	}

	public static void register() {
		render();
	}

	public static void registerComplete(@Required String user_name,
			@Required String password1,
			@Required String password2,
			@Required String email,
			@Required String role,
			@Required String name) {
		
		if(validation.hasErrors()) {
			flash.error("Please type again!");
			register();
		}else {
			if (password1.equals(password2)) {
				if (role.equals("club")) {
					ClubUser user = new ClubUser(user_name, password1, email, name);
					user.save();
					connect(user);
					index();
				}
				else if(role.equals("retailer")) {
					RetailUser user = new RetailUser(user_name, password1, email, name);
					user.save();
					connect(user);
					index();
					
				}else {
					flash.error("Password is not the same!");
					register();
				}
			}else {
				flash.error("Password is not the same!");
				register();
			}
		}
	}

	static void connect(User user) {
		session.put("logged", user.id);
		setConnectedUser();
	}

	static User connectedUser() {
		String userId = session.get("logged");
		User user = null;

		if(userId != null) {
			try{
				user = User.findById(Long.parseLong(userId));
			}catch (Exception e){
				e.printStackTrace();
			}
		}
		return user;
	}

	static String identifyUser() {
		String role = null;
		if(connectedUser != null) {
			if (connectedUser.getUserRole() == Role.CLUB) {
				role = "Club";
			}
			else if (connectedUser.getUserRole() == Role.RETAILER) {
				role = "Retailer";
			}
		}
		return role;
	}
	
	public static void index() {
		if(connectedUser == null) {
			renderTemplate("Application/index.html");
		} else if(connectedUser.getUserRole() == Role.CLUB) {
			Club.index();
		} else if (connectedUser.getUserRole() == Role.RETAILER) {
			Retailer.index();
		} else {
			throw new IllegalArgumentException("Illegal role " + connectedUser.getUserRole());
		}		
	}
}